package com.java.dao.imp;

import com.java.dao.BaseAdminDao;
import com.java.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @Author Clarklevis
 * @Date 2021/5/24
 */
public class AdminDaoMysql implements BaseAdminDao {

    private static final String SQL_UPDATE_LOGIN_TIME = "update eadmin set logintime = ?, loginip = ? where username = ?";
    private static final String SQL_LOGIN = "select id from eadmin where username = ? and password = ?";

    /**
     * 根据用户名更新时间和登录ip
     *
     * @param username 用户名
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setDate(1,new java.sql.Date(date.getTime()));//将util.data转化为sql.date
            state.setString(2,ip);
            state.setString(3,username);
            state.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtil.close(connection, state, null);
        }
    }

    /**
     * 管理员根据账号密码登录
     *
     * @param username 账号
     * @param password 密码
     * @return 登录的结果，true表示成功
     */
    @Override
    public boolean login(String username, String password) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet resultSet = null;
        try {
            state = connection.prepareStatement(SQL_LOGIN);
            state.setString(1, username);
            state.setString(2, password);
            resultSet = state.executeQuery();
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtil.close(connection, state, resultSet);
        }
        return false;
    }
}
